﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FzWeb.Models;
using System.Text.RegularExpressions;

namespace FzWeb.Filter
{
    public class AuthFilter : AuthorizeAttribute, IAuthorizationFilter
    {

        private UserService userService = new UserService();
        #region IAuthorizationFilter 成员

        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Session["user"] == null)
            {
                
                filterContext.HttpContext.Response.Redirect("/");
            }
            string actionMethod = filterContext.RouteData.Values["controller"].ToString().ToLower() + "/" + filterContext.RouteData.Values["action"].ToString().ToLower();
            User user = filterContext.HttpContext.Session["user"] as User;
            if (!user.RoleReference.IsLoaded)
            {
                user.RoleReference.Load();
            }
            if (!user.Role.Module.IsLoaded)
            {
                user.Role.Module.Load();
            }
            
            //判断否定的
            foreach (var m in user.Role.Module.Where(c => c.Deny == true))
            {
                if (Regex.IsMatch(actionMethod.ToLower(), m.Pattern.ToLower()))
                {
                    filterContext.HttpContext.Response.Redirect("/");
                }
            }

            //判断肯定的
            foreach (var m in user.Role.Module.Where(c=>c.Deny==false))
            {
                if (Regex.IsMatch(actionMethod.ToLower(), m.Pattern.ToLower()))
                {
                    return;
                }
            }
            filterContext.HttpContext.Response.Redirect("/");
        }

        #endregion
    }
}
